package cn.com.dycc.sys_manage.usersysmanagement.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.baidu.yun.push.exception.PushClientException;
import com.baidu.yun.push.exception.PushServerException;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import cn.com.dycc.common.controller.BaseController;
import cn.com.dycc.sys_manage.menusysmanagement.service.MenuService;
import cn.com.dycc.sys_manage.usersysmanagement.entity.Conver;
import cn.com.dycc.sys_manage.usersysmanagement.entity.UserIndexResult;
import cn.com.dycc.sys_manage.usersysmanagement.entity.UserInfo;
import cn.com.dycc.sys_manage.usersysmanagement.entity.UserInfoAccount;
import cn.com.dycc.sys_manage.usersysmanagement.entity.UserPart;
import cn.com.dycc.sys_manage.usersysmanagement.entity.UserResult;
import cn.com.dycc.sys_manage.usersysmanagement.param.AddUserParam;
import cn.com.dycc.sys_manage.usersysmanagement.param.UserParam;
import cn.com.dycc.sys_manage.usersysmanagement.service.CodeException;
import cn.com.dycc.sys_manage.usersysmanagement.service.PasswordNotFoundException;
import cn.com.dycc.sys_manage.usersysmanagement.service.UserNotFoundException;
import cn.com.dycc.sys_manage.usersysmanagement.service.UserService;
import cn.com.dycc.util.ImageUtil;
import cn.com.dycc.util.JsonObjectResult;
/**
 * 用户信息控制层
 * Description: 
 * Author: linfangan
 * Version: 1.0
 * Create Date Time: 2017年8月15日 上午8:37:57.
 * Update Date Time: 
 * @see
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController{
	
	@Resource(name="userService")
	private UserService userService;
	
	@Resource(name="menuService")
	private MenuService menuService;
	
	//增加用户(用户基本信息，用户角色权限，用户子账户表)
	@RequestMapping(value="/adduser.do")
	@ResponseBody
	public JsonObjectResult addUser(@RequestBody AddUserParam user,HttpServletRequest request){
		String org_id = request.getSession().getAttribute("org_id").toString();
		String create_user = request.getSession().getAttribute("id").toString();
		user.setOrg_id(org_id);
		user.setCreate_user(create_user);
//		System.out.println(user);
		String message = userService.insertUser(user);
//		System.out.println("adduser"+" "+user);
//		System.out.println("message="+message);
		return new JsonObjectResult(message);
	}
	
	
	//根据id查找用户信息(用户基本信息，用户角色权限，用户子账户表)
	@RequestMapping("/findall.do")
	@ResponseBody
	public JsonObjectResult findAllUserMessageByUserId(HttpServletRequest request,String id){
		UserResult userMessage = userService.findAllUserMessageByUserId(request,id);
//		System.out.println(userMessage);
		return new JsonObjectResult(userMessage);
	}

	//查询所有用户信息
	@RequestMapping("/allinfo.do")
	@ResponseBody
	public JsonObjectResult findAllUserInfo(HttpServletRequest request,String state){
		String org_id = request.getSession().getAttribute("org_id").toString();
		List<UserResult> list = userService.allUserinfo(org_id,state);
		return new JsonObjectResult(list);
	}
	
	
	//删除用户信息
	@RequestMapping("/deluser.do")
	@ResponseBody
	public JsonObjectResult deleteUserInfoByUserId(HttpServletRequest request,String userId){
		String message = userService.deleteUserInfoByUserId(request,userId);
		return new JsonObjectResult(message);
	}
//		
	//更新用户(用户基本信息，用户角色权限，用户子账户表)
	@RequestMapping(value="/upuser.do")
	@ResponseBody
	@JsonIgnoreProperties(ignoreUnknown = true)
	public JsonObjectResult updateUserInfoByUserId(@RequestBody AddUserParam user,HttpServletRequest request){
		String org_id = request.getSession().getAttribute("org_id").toString();
		String update_user_id = request.getSession().getAttribute("id").toString();
		user.setOrg_id(org_id);
		user.setUpdate_user_id(update_user_id);
		String message = userService.updateUserInfoByUserId(user);
		return new JsonObjectResult(message);
	}
	
//	
//	//查找所有用户信息(联系方式，用户基本信息，用户角色权限，用户子账户表)
//	@SuppressWarnings("unchecked")
//	@RequestMapping("/alluserinfo.do")
//	@ResponseBody
//	public JsonResult selAllUserInfo(HttpServletRequest request){
//		List<Integer> bindRoleNo =(List<Integer>)request.getSession().getAttribute("role_no");
//		Integer bindTop_dept_no = (Integer)request.getSession().getAttribute("top_dept_no");
//		List<User> allUserInfo = userService.selAllUserInfo(bindRoleNo,bindTop_dept_no);
//		return new JsonResult(allUserInfo);
//	}
//	
	
	//批量删除用户信息
	@RequestMapping("/delbatchuser.do")
	@ResponseBody
	public JsonObjectResult deleteBatchUser(HttpServletRequest request,String ...ids){
		String message = userService.delBatchUser(request,ids);
		return new JsonObjectResult(message);
	}
	
	
//	
//	
				@RequestMapping("/login.do")
				@ResponseBody
				public JsonObjectResult login(String account,String password,HttpServletRequest req,String code){
					HttpSession session = req.getSession();
					
//					System.out.println("7.......");
					
					//Enumeration   typestr = request.getHeaderNames(); 
					String s1 = req.getHeader("user-agent");
					
//					System.out.println("s1="+s1); 
					if(s1.contains("okhttp/3.6.0")||s1.contains("Android")){
						int deviceType = 3;
						session.setAttribute("deviceType", deviceType);
						boolean b  = userService.login(account, password, req);
						//System.out.println("手机");
						if(b){
							String sys_flag = "2";
							List<Object> list = menuService.findMenuInfoByMap(req, sys_flag);
//							System.out.println("list="+list);
							return new JsonObjectResult(list);
						}			
						return new JsonObjectResult(s1);
					}
					
					if(s1.contains("iPhone")||s1.contains("iPad")){
						int deviceType = 4;
						session.setAttribute("deviceType", deviceType);
						
						boolean b  = userService.login(account, password, req);
						//System.out.println("手机");
						if(b){
							String sys_flag = "2";
							List<Object> list = menuService.findMenuInfoByMap(req, sys_flag);
//							System.out.println("list="+list);
							return new JsonObjectResult(list);
						}			
						return new JsonObjectResult(s1);
					}
					
					//以下为PC端处理
					String imgcode = (String)session.getAttribute("imgcode");
					if(imgcode==null){
						return new JsonObjectResult(s1);
					}
					if(imgcode==null){
						CodeException e =  new CodeException("请刷新验证码");
						return new JsonObjectResult(4,e);
					}
					if(!imgcode.equals(code)){
						CodeException e =  new CodeException("验证码错误");
						return new JsonObjectResult(4,e);			
					}
					
					boolean b = userService.login(account, password,req);
					//从集合取值绑定到session
					
//								for(Map<String,Object> map:list){
//									System.out.println(map);
//								}
					if(b){
						String sys_flag2 = "1";
						List<Object> list2 = menuService.findMenuInfoByMap(req, sys_flag2);
						return new JsonObjectResult(list2);
					}
					return new JsonObjectResult(s1);
				}
	
	
	
	@ExceptionHandler(PasswordNotFoundException.class)
	@ResponseBody
	public JsonObjectResult passwordExceptoin(PasswordNotFoundException e) {
		e.printStackTrace();
		return new JsonObjectResult(3,e);
	}
	
	@ExceptionHandler(ParseException.class)
	@ResponseBody
	public JsonObjectResult ParseException(ParseException e){
		e.printStackTrace();
		return new JsonObjectResult(6,e);
	}
	
	@RequestMapping(produces="image/png",value="/code.do")
	@ResponseBody
	public byte[] code(HttpServletRequest req){
		Object[] objs = ImageUtil.createImage();
//		System.out.println("1="+objs[0]);
//		System.out.println("2="+objs[1]);
		
		//将验证码存入session
		HttpSession session = req.getSession();
		session.setAttribute("imgcode", objs[0]);		
		//1.创建图片对象
		BufferedImage img = (BufferedImage) objs[1];
		byte[] ary = null;
		try {
			ary = ImageUtil.imgToByteArray(img);
//			System.out.println("3="+ary.length);
		} catch (IOException e) {			
			e.printStackTrace();
			throw new RuntimeException("获取验证码失败");
		}
		return ary;
	}
	

	@RequestMapping("/exit.do")
	@ResponseBody
	public JsonObjectResult exit(HttpServletRequest req){		
		boolean b = userService.exit(req);
		return new JsonObjectResult(b);
	}
	
	@RequestMapping("/checkedlogin.do")
	@ResponseBody
	public JsonObjectResult checkedLogin(HttpServletRequest req){
		HttpSession session = req.getSession();
		//System.out.println(session);
		String user_id = session.getAttribute("id").toString();
		if(user_id==null){
			session.invalidate();
			return new JsonObjectResult(false);
		}
		//System.out.println(session);
		return new JsonObjectResult(true);
	}
	
	//用户列表查询 名字查询
	//2018-05-08改动
	@RequestMapping("/condfinduser.do")
	@ResponseBody
	public JsonObjectResult findUserByArray(HttpServletRequest request,UserParam userParam,String state){
//		String bindTop_dept_no = request.getSession().getAttribute("top_dept_no").toString();
		String org_id = request.getSession().getAttribute("org_id").toString();
//		userParam.setTop_dept_no(bindTop_dept_no);
		List<UserResult> listUser = userService.findUserByArray(request,userParam,org_id,state);
		String count = userService.findUserArrayCount(userParam, org_id, state);
		return new JsonObjectResult(count,listUser);
	}
	
	//查询角色101和102内的人员信息
	@RequestMapping("/lindao.do")
	@ResponseBody
	public JsonObjectResult findUserInfoByRoleUser(String dept_no,String user_id){
		List<UserInfo> listUser = userService.findUserInfoByRoleUser(dept_no, user_id);
		return new JsonObjectResult(listUser);
	}
	
	//删除用户实际上是更新用户state状态
	@RequestMapping("/upstate.do")
	@ResponseBody
	public JsonObjectResult updateState(HttpServletRequest request,String id) throws UserNotFoundException, IOException{
		String mes = userService.updateState(request,id);
		return new JsonObjectResult(mes);
	}
	
	//批量删除用户实际上是批量更新用户state状态
	@RequestMapping("/arrupstate.do")
	@ResponseBody
	public JsonObjectResult arrUpdateState(HttpServletRequest request,String ...ids) throws UserNotFoundException, IOException, PushServerException, PushClientException{
		String mes = userService.arrupdateState(request,ids);
		return new JsonObjectResult(mes);
	}
	
	//启用用户实际上是更新用户state状态
	@RequestMapping("/enable.do")
	@ResponseBody
	public JsonObjectResult enabledState(HttpServletRequest request,String id){
		String mes = userService.enabledState(request,id);
		return new JsonObjectResult(mes);
	}
	
	
	//根据部门查询该部门下人员
	@RequestMapping("/throwuser.do")
	@ResponseBody
	public JsonObjectResult throwDeptFindUser(HttpServletRequest request,String dept_no){
		List<UserInfoAccount> list = userService.throwDeptFindUser(request,dept_no);
		return new JsonObjectResult(list);
	}
	
	//查询101和102内的全部领导
	@RequestMapping("/leader.do")
	@ResponseBody
	public JsonObjectResult findAlleader(HttpServletRequest request){
		String org_id = request.getSession().getAttribute("org_id").toString();
		List<UserInfo> list = userService.findAlleader(org_id);
		return new JsonObjectResult(list);
	}
	
	//查询除了权限为0的所有用户
	@RequestMapping("/cxuser.do")
	@ResponseBody
	public JsonObjectResult CxUserXinXi(HttpServletRequest request){
		String org_id = request.getSession().getAttribute("org_id").toString();
		List<UserInfoAccount> list = userService.CxUserXinXi(org_id);
		return new JsonObjectResult(list);
	}
	
	//查询除了权限为0的用户，包首字母
	@RequestMapping("/conver.do")
	@ResponseBody
	public JsonObjectResult ConverName(HttpServletRequest request){
		String org_id = request.getSession().getAttribute("org_id").toString();
		List<Conver> list = userService.conver(org_id);
		return new JsonObjectResult(list);
	}
	
	//根据人物id查询人物信息,个人中心
	@RequestMapping("/center.do")
	@ResponseBody
	public JsonObjectResult reasonIdfindUser(HttpServletRequest request){
		String org_id = request.getSession().getAttribute("org_id").toString();
		String id = request.getSession().getAttribute("id").toString();
		UserPart userPart = userService.reasonIdfindUser(id, org_id);
		return new JsonObjectResult(userPart);
	}
	
	//更新密码 lisuoding
	@RequestMapping("/updatepass.do")
	@ResponseBody
	public JsonObjectResult updatepass(HttpServletRequest request,String password,String oldpassword) throws UserNotFoundException, IOException{
		String userId =request.getSession().getAttribute("id").toString();
		String i =userService.updatepassword(request,password,oldpassword,userId);
		return new JsonObjectResult(i);
	}
	
	//退出登录 lisuoding
	@RequestMapping("/exit1.do")
	@ResponseBody
	public JsonObjectResult exit1(HttpServletRequest req){		
		boolean b = userService.exit1(req);
		return new JsonObjectResult(b);
	}
	
	//自动登录	
		@RequestMapping("/aotoLogin.do")
		@ResponseBody
		public JsonObjectResult autoLogin(String account,String password,HttpServletRequest req,String code){
			HttpSession session = req.getSession();		
			String s1 = req.getHeader("user-agent");
			if(s1.contains("okhttp/3.6.0")||s1.contains("Android")){
				int deviceType = 3;
				session.setAttribute("deviceType", deviceType);
				
				boolean b  = userService.autoLogin(account, password, req);
				//System.out.println("手机");
				if(b){
					String sys_flag = "2";
					List<Object> list = menuService.findMenuInfoByMap(req, sys_flag);
		//			System.out.println("list="+list);
					return new JsonObjectResult(list);
				}			
				return new JsonObjectResult(s1);
			}
			
			if(s1.contains("iPhone")||s1.contains("iPad")){
				int deviceType = 4;
				session.setAttribute("deviceType", deviceType);
				
				boolean b  = userService.autoLogin(account, password, req);
				//System.out.println("手机");
				if(b){
					String sys_flag = "2";
					List<Object> list = menuService.findMenuInfoByMap(req, sys_flag);
		//			System.out.println("list="+list);
					return new JsonObjectResult(list);
				}			
				return new JsonObjectResult(s1);
			}
			
					
			return new JsonObjectResult(s1);
		
		}
	
	
	//登录用户主页信息
	@RequestMapping("findindex.do")
	@ResponseBody
	public JsonObjectResult finindex(HttpServletRequest request){
		String id = request.getSession().getAttribute("id").toString();
		UserIndexResult userIndexInfo = userService.indexUserInfo(id);
		return new JsonObjectResult(userIndexInfo);
	}
	
	//修改头像
	@RequestMapping("updateface.do")
	@ResponseBody
	public JsonObjectResult updateface(HttpServletRequest request,@RequestParam(value="file",required=false)MultipartFile file) throws UserNotFoundException, IllegalStateException, IOException{
		String id = request.getSession().getAttribute("id").toString();
		String mes = userService.updateFace(id, file);
		return new JsonObjectResult(mes);
	}
	
	//查询所有用户列表，用户添加用户权限,除了id为0的用户
	@RequestMapping("userline.do")
	@ResponseBody
	public JsonObjectResult findAllUserLine(HttpServletRequest request,String role_no,Integer page,Integer limit,String username) throws UserNotFoundException, IllegalStateException, IOException{
		String org_id = request.getSession().getAttribute("org_id").toString();
		String count = userService.findUserLineCount(request,username);
		List<Object> mes = userService.UserLine(org_id, role_no, page, limit,username);
		return new JsonObjectResult(count,mes);
	}
	
	
	//根据id重置用户密码
	@RequestMapping("reset.do")
	@ResponseBody
	public JsonObjectResult restPassword(HttpServletRequest request,String user_id){
		String mes = userService.restPassword(request,user_id);
		return new JsonObjectResult(mes);
	}
	
	//用于user查询多条件动态查询多表 将已经是党员的用户排除在外
	@RequestMapping("/allusernotpartyuser.do")
	@ResponseBody
	public JsonObjectResult findUserByArrayNotInPartyUser(HttpServletRequest request,UserParam userParam,String state){
		List<UserResult> listUser = userService.findUserByArrayNotInPartyUser(request,userParam,state);
		String count = userService.findUserByArrayNotInPartyUserCount(request,userParam,state);
		return new JsonObjectResult(count,listUser);
	}
	
	
}


